package io.renren.modules.driver.service.impl;

import com.alibaba.fastjson.JSONArray;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.api.dao.PsOrderLogisticsRecordDao;
import io.renren.modules.api.dao.PsOrderRouteSectionDao;
import io.renren.modules.api.dao.UserCollectDriverDao;
import io.renren.modules.api.dao.UserDao;
import io.renren.modules.api.entity.PsOrderLogisticsRecordEntity;
import io.renren.modules.api.entity.PsOrderRouteSectionEntity;
import io.renren.modules.api.entity.UserCollectDriverEntity;
import io.renren.modules.api.entity.UserEntity;
import io.renren.modules.api.service.IPayService;
import io.renren.modules.psorder.dao.PsOrderDao;
import io.renren.modules.psorder.entity.PsOrderEntity;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import io.renren.modules.driver.dao.SjDriverDao;
import io.renren.modules.driver.entity.SjDriverEntity;
import io.renren.modules.driver.service.SjDriverService;
import org.springframework.transaction.annotation.Transactional;


@Service("sjDriverService")
public class SjDriverServiceImpl implements SjDriverService {
	@Autowired
	private SjDriverDao driverDao;
	@Autowired
	private PsOrderDao psOrderDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserCollectDriverDao userCollectDriverDao;
	@Autowired
	private PsOrderRouteSectionDao psOrderRouteSectionDao;
	@Autowired
	private PsOrderLogisticsRecordDao psOrderLogisticsRecordDao;
	@Autowired
	private IPayService payService;

	@Override
	public SjDriverEntity queryObject(Long id){
		return driverDao.queryObject(id);
	}
	
	@Override
	public List<SjDriverEntity> queryList(Map<String, Object> map){
		return driverDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return driverDao.queryTotal(map);
	}
	
	@Override
	public void save(SjDriverEntity sjDriver){
		driverDao.save(sjDriver);
	}
	
	@Override
	public void update(SjDriverEntity sjDriver){
		driverDao.update(sjDriver);
	}
	
	@Override
	public void delete(Long id){
		driverDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Long[] ids){
		driverDao.deleteBatch(ids);
	}

	@Override
	public SjDriverEntity queryObjectByUserName(String username) {
		return driverDao.queryObjectByUserName(username);
	}

	@Override
	@Transactional
	public void receivePstOrder(PsOrderEntity psOrder, SjDriverEntity driver,String longitude, String latitude) {
		//接单人ID
		psOrder.setDriverId(driver.getId());
		//接单人姓名
		psOrder.setDriverName(driver.getRealname());
		//接单人电话
		psOrder.setDriverTel(driver.getUsername());
		//订单当前经度
		psOrder.setCurLng(longitude);
		//订单当前纬度
		psOrder.setCurLat(latitude);
		//订单状态 已经接单
		psOrder.setOrderStatus("9");

		int status = psOrderDao.receivePsOrder(psOrder);
        if (status == 0) {
        	throw new RRException("抱歉,订单已被接了!",620);
		}

		//判断是否是用户的收藏司机
		Map<String,Object> params = new HashedMap();
		params.put("userId",psOrder.getUserId());
		params.put("driverId",driver.getId());
		List<UserCollectDriverEntity> userCollectDrivers = userCollectDriverDao.queryList(params);
        if ( userCollectDrivers.size()> 0 ) {  //说明已收藏该司机
			psOrder.setCollected(true);
		}

		//删除高德云位置信息
//		int operation = AutoNaviUtils.DeleteDataById(driver.getGaoId());
//		if (operation == 1) {
//			driver.setGaoId(null);
//			driver.setDriveStatus("2");
//			driverDao.update(driver);
//		} else {
//			throw new RRException("接单失败,删除高德云位置失败!",-4);
//		}
		//接单时间
		psOrder.setReceiveTime(new Date());
		psOrderDao.update(psOrder);

		//记录到订单跟踪表
		PsOrderLogisticsRecordEntity psOrderLogisticsRecordEntity = new PsOrderLogisticsRecordEntity();
		psOrderLogisticsRecordEntity.setOrdernum(psOrder.getOrdernum());
		psOrderLogisticsRecordEntity.setRecordTime(new Date());
		psOrderLogisticsRecordEntity.setType("0");
		psOrderLogisticsRecordEntity.setContent("司机接单");
		psOrderLogisticsRecordDao.save(psOrderLogisticsRecordEntity);

		//推送告知用户订单已被接
		UserEntity user = userDao.queryObject(psOrder.getUserId());
        String userRegistrationId = user.getRegistrationId();
        if (userRegistrationId == null || "".equals(userRegistrationId)) {
            throw new RRException("推送时用户的极光Id为null或空串",-5);
        }
//		List<Map<String,Object>> destinationList = psOrderRouteSectionDao.queryDestinationsByOrderNum(psOrder.getOrdernum());
//		JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
		try {
			QmSendPush.sendOrderReceivedToUser(userRegistrationId,psOrder,null);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

	}

	@Override
	@Transactional
	public void completedPsOrder(PsOrderEntity psOrder,SjDriverEntity driver,BigDecimal extraCharge, String extraChargeNote) {
        psOrder.setExtraCharge(extraCharge);
        psOrder.setExtraChargeNote(extraChargeNote);
        psOrder.setOrderStatus("1");
        psOrder.setCreateTime(new Date());
		psOrderDao.update(psOrder);
        //完成订单后,司机状态改为“未出车”
        driver.setDriveStatus("0");
		driverDao.update(driver);
		//推送乘客订单完成，让其付款


	}

	@Override
	@Transactional
	public void startCalculateMileage(PsOrderEntity psOrder, String curLng, String curLat) {
		psOrder.setCurLng(curLng);
		psOrder.setCurLat(curLat);
		psOrder.setStartTime(new Date()); //记录开始出发时间
		psOrder.setOrderStatus("6"); //已出发
		psOrderDao.update(psOrder);

		//记录到订单跟踪表
		PsOrderLogisticsRecordEntity psOrderLogisticsRecordEntity = new PsOrderLogisticsRecordEntity();
		psOrderLogisticsRecordEntity.setOrdernum(psOrder.getOrdernum());
		psOrderLogisticsRecordEntity.setRecordTime(new Date());
		psOrderLogisticsRecordEntity.setType("1");
		psOrderLogisticsRecordEntity.setContent("已出发");
		psOrderLogisticsRecordDao.save(psOrderLogisticsRecordEntity);

		UserEntity user = userDao.queryObject(psOrder.getUserId());
		//推送乘客开始出发，计算里程
		try {
			QmSendPush.sendOrderStartedToUser(user.getRegistrationId(), psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}


	}

	@Override
	@Transactional
	public void cancelPsOrder(PsOrderEntity psOrder,SjDriverEntity driver) {
		psOrder.setOrderStatus("4"); //订单状态改为已取消(司机)
		psOrderDao.update(psOrder);

		driver.setGaoId(null);
		driver.setDriveStatus("0");
		driverDao.update(driver);

		UserEntity user = userDao.queryObject(psOrder.getUserId());
		try {
			QmSendPush.sendOrderCanceledToPassenger(user.getRegistrationId(),psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

	}

	@Override
	public PsOrderEntity completeUnloading(PsOrderEntity psOrder, SjDriverEntity driver) {
		psOrder.setCompleteTime(new Date());//卸货完成时间
        //计算超时等待时间
		int waitTimeStart = DateUtils.getMinutesSub(DateUtils.formatTime(psOrder.getArriveStartTime()),
				  DateUtils.formatTime(psOrder.getStartTime())); //
		int waitTimeEnd = DateUtils.getMinutesSub(DateUtils.formatTime(psOrder.getArriveEndTime()),
				DateUtils.formatTime(psOrder.getCompleteTime()));
		psOrder.setWaitMinutes(waitTimeStart + waitTimeEnd);
		//计算超时等待价格
		psOrder.setWaitPrice(new BigDecimal(0));
		if (psOrder.getWaitMinutes()> 60) {
			psOrder.setWaitPrice(new BigDecimal(psOrder.getWaitMinutes() - 60));
		}
		//计算订单总价 = 超出里程费 + 总价 + 有偿等待价
		BigDecimal realDistanceB = (DataTypeUtils.stringToBigDecimal(psOrder.getRealdistance())).divide(new BigDecimal(1000));
		BigDecimal passKiloMetres = new BigDecimal(0); //超里程数(公里),默认为0表示默认5公里内
		if (realDistanceB.compareTo(new BigDecimal(5)) > 0 ) {
			passKiloMetres = realDistanceB.subtract(new BigDecimal(5));
		}
		psOrder.setOverMilege(passKiloMetres);
		psOrder.setTotalPrice(passKiloMetres.multiply(psOrder.getMilegeUnitPrice()).
				add(psOrder.getStartingPrice()).add(psOrder.getWaitPrice()));
		psOrder.setOrderStatus("1"); //到达目的地
		psOrderDao.update(psOrder);

		return psOrder;
	}

	@Override
	public PsOrderEntity modifyTotalPrice(PsOrderEntity psOrder, BigDecimal extraCharge, String extraChargeNote) {
//		if(psOrder.getSumModifyPrice() == null) {	//多次修改价格总和
//			psOrder.setSumModifyPrice(extraCharge);
//		} else {
//			psOrder.setSumModifyPrice(psOrder.getSumModifyPrice().add(extraCharge));
//		}
		if(psOrder.getExtraCharge() == null) {
			psOrder.setExtraCharge(extraCharge);
		} else {
			psOrder.setExtraCharge(psOrder.getExtraCharge().add(extraCharge));
		}
		if (psOrder.getExtraChargeNote() == null){
			psOrder.setExtraChargeNote(extraChargeNote);
		} else {
			psOrder.setExtraChargeNote(psOrder.getExtraChargeNote()+","+extraChargeNote);
		}
		psOrder.setTotalPrice(psOrder.getTotalPrice().add(extraCharge));
		psOrderDao.update(psOrder);

		//反馈用户,价格已修改
		UserEntity user = userDao.queryObject(psOrder.getUserId());
		try {
			QmSendPush.sendToUserPsOrderPriceModified(user.getRegistrationId(),psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

		return psOrder;
	}

	@Override
	@Transactional
	public void goToCharge(PsOrderEntity psOrder) {
		//改变订单为待收费状态
		psOrder.setOrderStatus("8");
		psOrderDao.update(psOrder);

		//发推送给用户去支付
		UserEntity user = userDao.queryObject(psOrder.getUserId());
		try {
			QmSendPush.sendPsOrderToUserForPay(user.getRegistrationId(),psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

	}

	@Override
	@Transactional
	public void confirmCash(PsOrderEntity psOrder) {
		//改变订单为已收费
		psOrder.setOrderStatus("2");
		psOrder.setPayType("cash");
		psOrder.setPayTime(new Date());
		psOrder.setPayRealymoney(psOrder.getTotalPrice().doubleValue());
		psOrderDao.update(psOrder);

		payService.updateOrAddDriverStatistics(psOrder,"cash");

		//反馈用户订单已支付
		UserEntity user = userDao.queryObject(psOrder.getUserId());
		try {
			QmSendPush.sendToUserPsOrderPaid(user.getRegistrationId(),psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

	}

	@Override
	@Transactional
	public void arriveStart(PsOrderEntity psOrder) {
		psOrder.setArriveStartTime(new Date()); //记录到达发货地时间
		psOrder.setOrderStatus("5"); //设置订单状态为5:到达发货点
		psOrderDao.update(psOrder);

		//记录到订单跟踪表
		PsOrderLogisticsRecordEntity psOrderLogisticsRecordEntity = new PsOrderLogisticsRecordEntity();
		psOrderLogisticsRecordEntity.setOrdernum(psOrder.getOrdernum());
		psOrderLogisticsRecordEntity.setRecordTime(new Date());
		psOrderLogisticsRecordEntity.setType("2");
		psOrderLogisticsRecordEntity.setContent("司机到达发货地等待装货");
		psOrderLogisticsRecordDao.save(psOrderLogisticsRecordEntity);

		//反馈用户司机已到达发货点
		UserEntity user = userDao.queryObject(psOrder.getUserId());
		String userRegistrationId = user.getRegistrationId();
		if (userRegistrationId == null || "".equals(userRegistrationId)) {
            throw new RRException("推送时用户的极光Id为null或空串",-5);
        }
		try {
			QmSendPush.sendToUserArriveStart(userRegistrationId,psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

	}

	@Override
	@Transactional
	public void arriveEnd(PsOrderEntity psOrder) {
		psOrder.setArriveEndTime(new Date()); //记录到达目的地时间
		psOrder.setOrderStatus("1"); //设置订单状态为1:到达目的地
		psOrderDao.update(psOrder);

		//反馈用户司机已到目的地
		UserEntity user = userDao.queryObject(psOrder.getUserId());
        String userRegistrationId = user.getRegistrationId();
        if (userRegistrationId == null || "".equals(userRegistrationId)) {
            throw new RRException("推送时用户的极光Id为null或空串",-5);
        }
		try {
			QmSendPush.sendToUserArriveEnd(userRegistrationId,psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

	}

	@Override
	public List<SjDriverEntity> queryCollectedListByUserId(Long userId) {
		return driverDao.queryCollectedListByUserId(userId);
	}

	@Override
	public Map<String, Object> queryMineInfo(Long driverId) {
		return driverDao.queryMineInfo(driverId);
	}

	@Override
	@Transactional
	public void modifyDestination(PsOrderEntity psOrder, SjDriverEntity driver,String psOrderRouteSections) {
//		String ditanceValue = AutoNaviUtils.calculateCarDistance(psOrder.getStartLng(),psOrder.getStartLat(),
//				psOrder.getEndLng(),psOrder.getEndLat()); //此为单目的地情况遗留
		List<PsOrderRouteSectionEntity> newList =
				JSONArray.parseArray(psOrderRouteSections,PsOrderRouteSectionEntity.class);
		//根据订单号查出目第一条路段，把终点设成起点，兼容后面代码(因为后面代码先写)
		PsOrderRouteSectionEntity psOrderRouteSection = psOrderRouteSectionDao.queryDesByOrderNumAndSortNum(psOrder.getOrdernum(),0);
		psOrderRouteSection.setEndName(psOrderRouteSection.getStartName());
		psOrderRouteSection.setEndNameDetail(psOrderRouteSection.getStartNameDetail());
		psOrderRouteSection.setEndLng(psOrderRouteSection.getStartLng());
		psOrderRouteSection.setEndLat(psOrderRouteSection.getStartLat());
		newList.add(0,psOrderRouteSection);

		//根据初步路段对象集合转成系统需要的路段对象集合
		for (int i=0 ; i < newList.size();i++) {
			if (i > 0){
				newList.get(i).setStartName(newList.get(i-1).getEndName());
				newList.get(i).setStartNameDetail(newList.get(i-1).getEndNameDetail());
				newList.get(i).setStartLng(newList.get(i-1).getEndLng());
				newList.get(i).setStartLat(newList.get(i-1).getEndLat());
				newList.get(i).setSortNum(newList.get(i).getSortNum()-1);
			}
		}
		newList.remove(0);

//		Map<String,Object> param = new HashMap<>();  //这种查法是按照id倒序排列的
//		param.put("orderNum",psOrder.getOrdernum());

		List<PsOrderRouteSectionEntity> oldList = psOrderRouteSectionDao.queryListByOrderNum(psOrder.getOrdernum());

		//情况一: 新目的地与旧目的地个数相等，直接把旧目的地地段值换成新的
		if (newList.size() == oldList.size()) {
			for (int i=0; i < oldList.size();i++ ) {
				if (oldList.get(i).getState().equals("0")) { //如该路段未达到，就可以修改
					oldList.get(i).setStartName(newList.get(i).getStartName()); 				//起点名称
					oldList.get(i).setStartNameDetail(newList.get(i).getStartNameDetail());		//起点名称详细
					oldList.get(i).setStartLng(newList.get(i).getStartLng());					//起点经度
					oldList.get(i).setStartLat(newList.get(i).getStartLat());					//起点纬度

					oldList.get(i).setEndName(newList.get(i).getEndName()); 				//终点名称
					oldList.get(i).setEndNameDetail(newList.get(i).getEndNameDetail());		//终点名称详细
					oldList.get(i).setEndLng(newList.get(i).getEndLng());					//终点经度
					oldList.get(i).setEndLat(newList.get(i).getEndLat());					//终点纬度
				}
			}
			//更新路段对象
			for (PsOrderRouteSectionEntity userFrequentlyRouteSectionEntity: oldList) {
				psOrderRouteSectionDao.update(userFrequentlyRouteSectionEntity);
			}

		}

		//情况二: 新目的地数量小于旧目的地
		if (newList.size() < oldList.size()) {
			for (int i=0; i < newList.size();i++ ) {
				if (oldList.get(i).getState().equals("0")) { //如该路段未达到，就可以修改
					oldList.get(i).setStartName(newList.get(i).getStartName());                //起点名称
					oldList.get(i).setStartNameDetail(newList.get(i).getStartNameDetail());        //起点名称详细
					oldList.get(i).setStartLng(newList.get(i).getStartLng());                    //起点经度
					oldList.get(i).setStartLat(newList.get(i).getStartLat());                    //起点纬度

					oldList.get(i).setEndName(newList.get(i).getEndName());                //终点名称
					oldList.get(i).setEndNameDetail(newList.get(i).getEndNameDetail());        //终点名称详细
					oldList.get(i).setEndLng(newList.get(i).getEndLng());                    //终点经度
					oldList.get(i).setEndLat(newList.get(i).getEndLat());                    //终点纬度
				}
			}
			//旧目的地删除多余的路段
			List<PsOrderRouteSectionEntity> tempList = new ArrayList<>(); //待删除集合
			for (int i = newList.size();i < oldList.size();i++ ) {
				tempList.add(oldList.get(i));
			}
			oldList.removeAll(tempList);
			//更新路段
			for (PsOrderRouteSectionEntity psOrderRouteSectionEntity: oldList) {
				psOrderRouteSectionDao.update(psOrderRouteSectionEntity);
			}
			//删除路段(多余的)
			for (int i=0;i < tempList.size();i++ ) {
				psOrderRouteSectionDao.delete(tempList.get(i).getId());
			}
		}

		//情况三: 新目的地数量大于旧目的地
		if (newList.size() > oldList.size()) {
			for (int i=0; i < oldList.size();i++ ) {
				if (oldList.get(i).getState().equals("0")) { //如该路段未达到，就可以修改
					oldList.get(i).setStartName(newList.get(i).getStartName());                //起点名称
					oldList.get(i).setStartNameDetail(newList.get(i).getStartNameDetail());        //起点名称详细
					oldList.get(i).setStartLng(newList.get(i).getStartLng());                    //起点经度
					oldList.get(i).setStartLat(newList.get(i).getStartLat());                    //起点纬度

					oldList.get(i).setEndName(newList.get(i).getEndName());                //终点名称
					oldList.get(i).setEndNameDetail(newList.get(i).getEndNameDetail());        //终点名称详细
					oldList.get(i).setEndLng(newList.get(i).getEndLng());                    //终点经度
					oldList.get(i).setEndLat(newList.get(i).getEndLat());                    //终点纬度
				}
			}
			//更新路段
			for (PsOrderRouteSectionEntity psOrderRouteSectionEntity: oldList) {
				psOrderRouteSectionDao.update(psOrderRouteSectionEntity);
			}
			//新增路段
			for (int i = oldList.size();i < newList.size();i++ ) {
				newList.get(i).setOrdernum(psOrder.getOrdernum());
				psOrderRouteSectionDao.save(newList.get(i));
			}

		}

		//计算订单距离(可能是多目的地),单位为米
		String ditanceValue = AutoNaviUtils.evaluateOrderDistance(newList);
		//设置订单距离,单位为千米
		psOrder.setDistance(DataTypeUtils.metresStringToKiloMeter(ditanceValue));

		//计算订单金额
		AutoNaviUtils.evaluateOrderMoneyByType2(psOrder,ditanceValue); //6种车型方案
		psOrderDao.update(psOrder);

		//反馈用户,目的地已修改
		UserEntity user = userDao.queryObject(psOrder.getUserId());
		try {
			QmSendPush.sendToUserPsOrderEndModified(user.getRegistrationId(),psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

	}

	@Override
	public List<Map<String,Object>> queryIncomeGroupByMonth(Long driverId) {
		return driverDao.queryIncomeGroupByMonth(driverId);
	}

	@Override
	public Map<String, Object> queryBalanceInfo(Long driverId) {
		return driverDao.queryBalanceInfo(driverId);
	}

	@Override
	public List<Map<String, Object>> queryIncomeDetail(Long driverId) {
		return driverDao.queryIncomeDetail(driverId);
	}

	@Override
	public Map<String, Object> queryIncomeByIuputMonth(Long driverId, String month) {
		return driverDao.queryIncomeByIuputMonth(driverId,month);
	}

	@Override
	public List<Map<String,Object>> queryIncomeDetailByIuputMonth(Long driverId, String month) {
		return driverDao.queryIncomeDetailByIuputMonth(driverId,month);
	}

	@Override
	@Transactional
	public void arriveDesByNum(PsOrderEntity psOrder, Integer arriveDesNum) {
		psOrder.setArriveDesNum(arriveDesNum);
		psOrderDao.update(psOrder);
		arriveDesNum--; //因为数据库存的时候sort_num是从0开始
		PsOrderRouteSectionEntity psOrderRouteSection = psOrderRouteSectionDao.queryDesByOrderNumAndSortNum(psOrder.getOrdernum(),arriveDesNum);
		psOrderRouteSection.setArriveTime(new Date());
		psOrderRouteSection.setState("1"); //设置状态为1-已到达
		psOrderRouteSectionDao.update(psOrderRouteSection);

		//记录到订单跟踪表
		PsOrderLogisticsRecordEntity psOrderLogisticsRecordEntity = new PsOrderLogisticsRecordEntity();
		psOrderLogisticsRecordEntity.setOrdernum(psOrder.getOrdernum());
		psOrderLogisticsRecordEntity.setRecordTime(new Date());
		psOrderLogisticsRecordEntity.setType("2");
		psOrderLogisticsRecordEntity.setContent("到达目的地，"+psOrderRouteSection.getEndName()+"，等待卸货");
		psOrderLogisticsRecordDao.save(psOrderLogisticsRecordEntity);

		//如果是最后一个目的地
		if (isTheLastDestination(psOrder.getOrdernum(),arriveDesNum)) {
			psOrder.setArriveEndTime(new Date()); //记录到达目的地时间
			psOrder.setOrderStatus("1"); //设置订单状态为1:到达目的地
			psOrderDao.update(psOrder);

			//反馈用户司机已到目的地
			UserEntity user = userDao.queryObject(psOrder.getUserId());
			String userRegistrationId = user.getRegistrationId();
			if (userRegistrationId == null || "".equals(userRegistrationId)) {
				throw new RRException("推送时用户的极光Id为null或空串",-5);
			}
			try {
				QmSendPush.sendToUserArriveEnd(userRegistrationId,psOrder);
			} catch (Exception e) {
				throw new RRException("极光推送发生异常",-2);
			}
			return ;
		}

		//告知用户已到达某个目的地
		UserEntity user = userDao.queryObject(psOrder.getUserId());
//		List<Map<String,Object>> destinationList = psOrderRouteSectionDao.queryDestinationsByOrderNum(psOrder.getOrdernum());
//		JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
		try {
			QmSendPush.sendToUserPsOrderArriveMidDes(user.getRegistrationId(),psOrder,++arriveDesNum,null);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}

	}

	@Override
	@Transactional
	public PsOrderEntity startDesByNum(PsOrderEntity psOrder, Integer arriveDesNum) {
		arriveDesNum--; //因为数据库存的时候sort_num是从0开始
		PsOrderRouteSectionEntity psOrderRouteSection = psOrderRouteSectionDao.queryDesByOrderNumAndSortNum(psOrder.getOrdernum(),arriveDesNum);
		psOrderRouteSection.setState("2"); //设置状态为2- 卸货完成
		psOrderRouteSection.setCompleteUnloadTime(new Date());
		psOrderRouteSectionDao.update(psOrderRouteSection);

		//记录到订单跟踪表
		PsOrderLogisticsRecordEntity psOrderLogisticsRecordEntity = new PsOrderLogisticsRecordEntity();
		psOrderLogisticsRecordEntity.setOrdernum(psOrder.getOrdernum());
		psOrderLogisticsRecordEntity.setRecordTime(new Date());
		psOrderLogisticsRecordEntity.setType("3");
		psOrderLogisticsRecordEntity.setContent("已完成");
		psOrderLogisticsRecordDao.save(psOrderLogisticsRecordEntity);

		arriveDesNum++;
		//如果是最后一个目的地
		if (isTheLastDestination(psOrder.getOrdernum(),arriveDesNum)) {
			int waitTime = 0;

			Map<String,Object> params = new HashMap<>();
			params.put("orderNum",psOrder.getOrdernum());
			List<PsOrderRouteSectionEntity> psOrderRouteSectionEntities = psOrderRouteSectionDao.queryList(params);
			for (PsOrderRouteSectionEntity psRouteSection : psOrderRouteSectionEntities){
				if (psRouteSection.getArriveTime() == null || psRouteSection.getCompleteUnloadTime() == null) {
					throw new RRException("统计等待时间出现null值",-8);
				}
				int minsTemp = DateUtils.getMinutesSub(DateUtils.formatTime(psRouteSection.getArriveTime()),
					DateUtils.formatTime(psRouteSection.getCompleteUnloadTime()));
					waitTime = waitTime + minsTemp;
			}
			psOrder.setWaitMinutes(waitTime);
			psOrder.setIsLastDes(true);
			psOrder.setOrderStatus("8");
			psOrderDao.update(psOrder);

			//告知用户已在某个目的地卸货完成
			UserEntity user = userDao.queryObject(psOrder.getUserId());
//			List<Map<String,Object>> destinationList = psOrderRouteSectionDao.queryDestinationsByOrderNum(psOrder.getOrdernum());
//			JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
			try {
				QmSendPush.sendToUserCompletedUnloadToStart(user.getRegistrationId(),psOrder,arriveDesNum,null);
			} catch (Exception e) {
				throw new RRException("极光推送发生异常",-2);
			}

			return psOrder;
		}

		//告知用户已在某个目的地卸货完成
		UserEntity user = userDao.queryObject(psOrder.getUserId());
//		List<Map<String,Object>> destinationList = psOrderRouteSectionDao.queryDestinationsByOrderNum(psOrder.getOrdernum());
//		JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
		try {
			QmSendPush.sendToUserCompletedUnloadToStart(user.getRegistrationId(),psOrder,arriveDesNum,null);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}
		return psOrder;

	}

    private boolean isTheLastDestination(String ordernum, Integer arriveDesNum){
	   int maxSortNum = psOrderRouteSectionDao.queryMaxSortNum(ordernum);
       if (arriveDesNum.intValue() == maxSortNum) {
			return true;
	   }
       return  false;
	}

	@Override
	@Transactional
	public void zbsfy(PsOrderEntity psOrder) {
		psOrderDao.update(psOrder);

		//反馈用户,订单暂不收费！
		UserEntity user = userDao.queryObject(psOrder.getUserId());
		String userRegistrationId = user.getRegistrationId();
		if (userRegistrationId == null || "".equals(userRegistrationId)) {
			throw new RRException("推送时用户的极光Id为null或空串",-5);
		}
		QmSendPush.sendToUserPsOrderZBSF(userRegistrationId,psOrder,null);

	}

	@Override
	public int realTimeLocation(SjDriverEntity driver, String longitude, String latitude, String address) {
		String gaoId = driver.getGaoId(); //高德云图id
		//待更新表数据参数拼接
		Map<String, Object> map = new HashMap();
		map.put("_id", gaoId);
		map.put("_location", longitude + "," + latitude);
		map.put("_address", address);
		JSONObject jsonObject = JSONObject.fromObject(map);
//		System.out.println("司机更新位置请求结果参数:"+ jsonObject.toString());
		String paraForSign = "data=" + jsonObject.toString() + "&key=" + QwjGlobal.AUTONAVI_WEB_KEY + "&tableid=" + QwjGlobal.AUTONAVI_HTTP_TABLE_ID
				+ QwjGlobal.AUTONAVI_WEB_PRIVATE_KEY;
		String sig = MD5Util.MD5Encode(paraForSign, "utf-8");

		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("data", jsonObject.toString());
		paraMap.put("key", QwjGlobal.AUTONAVI_WEB_KEY);
		paraMap.put("sig", sig);
		paraMap.put("tableid", QwjGlobal.AUTONAVI_HTTP_TABLE_ID);

		//发送 POST 请求
		String sr = HttpUtil.sendPost(QwjGlobal.AUTONAVI_HTTP_DATA_UPDATE_URL,paraMap);
		Map<String, Object> resultMap = QmJsonUtils.parseJSON2Map(sr);
//		System.out.println("司机更新位置请求结果:"+ resultMap);
		return Integer.valueOf(resultMap.get("status")+"");
	}

	@Override
	@Transactional
	public void realTimeLocationUpdatePsOrder(SjDriverEntity driver,PsOrderEntity psOrder,String longitude, String latitude, String address) {

		psOrder.setCurLng(longitude);
		psOrder.setCurLat(latitude);
		//计算实际行驶距离,采用累加行驶,现在已不需要，因为价格开始已定
//        String distance = AutoNaviUtils.calculateCarDistance(psOrder.getCurLng(), psOrder.getCurLat(),
//                curLng, curLat);
//        String realDistance = psOrder.getRealdistance();
//        if(realDistance == null || "".equals(realDistance.trim())){
//            realDistance = "0.0";
//        }
//        if(distance == null || "".equals(distance.trim())){
//            distance = "0.0";
//        }
//        float realDistanceF = Float.parseFloat(realDistance);
//        float distanceF = Float.parseFloat(distance)/1000;
//        float realDistanceFC = realDistanceF + distanceF;
//        psOrder.setRealdistance(realDistanceFC+"");
		psOrderDao.update(psOrder);

		//更新订单位置的同时更新高德云，调了这个就不用再调realTimeLocation方法了，为接单中再接单做准备
//		int status = realTimeLocation(driver,longitude,latitude,address);//更新高德云信息
//		if (status != 1) {
//			throw new RRException("更新高德云位置失败",-2);
//		}

	}


	/**
	 * 司机财务模块展示
	 */
	@Override
	public List<SjDriverEntity> sjFinancelist(Map<String, Object> map){
		return driverDao.sjFinancelist(map);
	}

	@Override
	public int sjFinancelistTotal(Map<String, Object> map){
		return driverDao.sjFinancelistTotal(map);
	}

}
